using System;
using System.Linq;
using System.Linq.Expressions;

namespace Webshop20.Application.Queries.Services
{
    public static class RepositoryExtensions
    {
        public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortField, bool orderByDescending) where T : class 
        {

            string command = orderByDescending ? "OrderByDescending" : "OrderBy";

            var type = typeof(T);
            var property = type.GetProperty(sortField);
            if (property == null)
                throw new InvalidOperationException("sortField");

            var parameter = Expression.Parameter(type, "p");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);

            var orderByExpression = Expression.Lambda(propertyAccess, parameter);

            var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType },

                                                   source.Expression, Expression.Quote(orderByExpression));

            return source.Provider.CreateQuery<T>(resultExpression); 


        
        }
    
    }
}